//
//  EpointPhoneMainViewController.m
//  EpointFrame5
//
//  Created by 李亚春 on 14-4-1.
//  Copyright (c) 2014年 Epoint. All rights reserved.
//

#import "EpointPhoneMainViewController.h"
#import "HJObjManager.h"
#import "EpointExtendIconView.h"
#import "EpointMainConfigModel.h"
#import "EpointBrowerViewController.h"
#import "EpointLoadMainConfigTask.h"
#import "EpointExtendAppConfig.h"
#import "EpointSettingViewController.h"
#import "EpointPlaySound.h"
#import "EAD_UserEditViewController.h"

#define LoadMainConfigTskId 1
#define User_GetInfo_TaskId 2
#define EpointRegistPushTokenTaskId 3
#define GenerationHeadImageTaskId 4

@interface EpointPhoneMainViewController ()<UIGestureRecognizerDelegate>
{
    UIScrollView *sv;
    UIView *uvScene;//头像
    HJObjManager *objMan;
    NSMutableArray *mainIconArray;
    UIView *uvMainIcon,*uvExtendIcon;
    UILabel *labExt;
    HJManagedImageV *headImgView;
}
@end

@implementation EpointPhoneMainViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self registePushToken];
    
    [self initHJManage];
    
    [self initControls];
    
    mainIconArray = [EpointLoadMainConfigTask getPhoneArrByStore];
    
    [self loadMainIconView];
    [self loadExtendIconView];
    
    //监听图标更新
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(update:) name:@"update" object:nil];
    
    //后台调用加载主界面模块配置数据库
    [self startTask:@"EpointLoadMainConfigTask" withParams:nil withTaskId:LoadMainConfigTskId];
    
    //同步数据
    [EpointSettingViewController synData:self];
    
}

//注册消息推送Token
-(void)registePushToken
{
    if ([NSLocalizedString(@"PushMessageEnable", @"") isEqualToString:@"1"])
    {
        [self startTask:@"EpointRegistPushTokenTask" withParams:nil withTaskId:EpointRegistPushTokenTaskId];
    }
    
}

//控件初始化
-(void)initControls
{
    [self.customBackground setImage:[UIImage imageNamed:@"img_main_bg2"]];
    self.navigationController.navigationBarHidden = NO;
    //隐藏返回按钮
    [self.navigationItem setHidesBackButton:YES];
    self.navigationItem.leftBarButtonItem = nil;
    
    //设置导航标题为应用标题
    self.title = [NSString stringWithFormat:@"%@",[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"]];
    
    [self.view setBackgroundColor:COLOR(237, 237, 237)];
    
    //增加一个滚动视图
    sv = [[UIScrollView alloc]initWithFrame:self.getFullContentFrame];
    [self.view addSubview:sv];
    
    uvScene = [[UIView alloc]initWithFrame:CGRectMake(0, 0, AppWidth, 120)];
    [sv addSubview:uvScene];
    
    UIImageView *scBg = [[UIImageView alloc]initWithFrame:uvScene.bounds];
    [scBg setImage:[UIImage imageNamed:@"img_main_bg1"]];
    [uvScene addSubview:scBg];
    
    UITapGestureRecognizer *singleFingerOne = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                                      action:@selector(handleSingleFingerEvent:)];
    singleFingerOne.numberOfTouchesRequired = 1; //手指数
    singleFingerOne.numberOfTapsRequired = 1; //tap次数
    singleFingerOne.delegate= self;
    
    CGFloat ivLength = 80;
    headImgView = [[HJManagedImageV alloc]initWithFrame:CGRectMake((AppWidth-ivLength)/5,(uvScene.frame.size.height-ivLength)/2,ivLength,ivLength)];
//    [headImgView.imageView addGestureRecognizer:singleFingerOne];//添加手指单击事件
    
    [uvScene addSubview:headImgView];
    
    [headImgView setImage:[UIImage imageNamed:@"img_man"]];
    [headImgView.imageView setContentMode:UIViewContentModeScaleAspectFill];
    headImgView.layer.masksToBounds = YES;
    headImgView.layer.cornerRadius = ivLength/2;
    headImgView.layer.borderWidth = 2;
    [headImgView.layer setBorderColor:[[UIColor whiteColor] CGColor]];
    
    headImgView.url = [NSURL URLWithString:[EpointBizTools getUserHeadImageDataUrl:[DBFrameService getUserGuid]]];
    [objMan manage:headImgView];
    
    [self startTask:@"EpointLoadUserHeadImageTask" withParams:nil withTaskId:GenerationHeadImageTaskId];
    
    UILabel *lbName = [[UILabel alloc]initWithFrame:CGRectMake(headImgView.frame.origin.x+headImgView.frame.size.width, (uvScene.frame.size.height-50)/2, 320-headImgView.frame.origin.x-headImgView.frame.size.width, 50)];
    lbName.backgroundColor = [UIColor clearColor];
    NSString *name = (NSString *)[DBFrameService getUserDefaults:Epoint_User_DisplayName];
    if (name.length<=3) {
        lbName.text = [NSString stringWithFormat:@"%@，欢迎您！",name];
    }
    else{
        lbName.text = [NSString stringWithFormat:@"%@\n欢迎您！",name];
    }
    lbName.numberOfLines = 2;
    lbName.textColor = [UIColor whiteColor];
    [lbName setFont:[UIFont boldSystemFontOfSize:17]];
    lbName.textAlignment = NSTextAlignmentCenter;
    [uvScene addSubview:lbName];
    
    [headImgView setCallbackOnImageTap:self method:@selector(handleSingleFingerEvent:)];
}

#pragma mark -头像点击事件
- (void)handleSingleFingerEvent:(UITapGestureRecognizer *)sender
{
//    NSString *name = (NSString *)[DBFrameService getUserDefaults:Epoint_User_DisplayName];
//    NSString *userguid = (NSString *)[DBFrameService getUserDefaults:Epoint_User_UserGuid];
//    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
//    [params setObject:name forKey:@"title"];
//    [params setObject:userguid forKey:@"userguid"];
//    EAD_UserEditViewController *dv = [[EAD_UserEditViewController alloc]init];
//    dv.passParam = params;
//    [self.navigationController pushViewController:dv animated:YES];
}

//初始化图片缓存管理器
-(void)initHJManage
{
    objMan = [[HJObjManager alloc] initWithLoadingBufferSize:20 memCacheSize:30];
    NSString* cacheDirectory = [NSHomeDirectory() stringByAppendingString:@"/Library/Caches/imgcache/flickr/"] ;
    HJMOFileCache* fileCache = [[HJMOFileCache alloc] initWithRootPath:cacheDirectory];
    objMan.fileCache = fileCache;
    fileCache.fileCountLimit = 100;
    fileCache.fileAgeLimit = 60*60*24*30; //1 week
    [fileCache trimCacheUsingBackgroundThread];
}

//监听更新
-(void)update:(NSNotification*)notify
{
    NSString *tips = [notify.userInfo objectForKey:@"tips"];
    NSString *type = [notify.userInfo objectForKey:@"type"];
    
    if ([type isEqualToString:@"mail"]) {
        if (tips.intValue>0) {
            [self changeIconTips:1 tips:tips hidden:NO];
        }
        else
        {
            [self changeIconTips:1 tips:tips hidden:YES];
        }
        
    }
    if ([type isEqualToString:@"waithandler"]) {
        if (tips.intValue>0) {
            [self changeIconTips:0 tips:tips hidden:NO];
        }
        else
        {
            [self changeIconTips:0 tips:tips hidden:YES];
        }
    }
}

//图标tips更新
-(void)changeIconTips:(int)index tips:(NSString *)tips hidden:(BOOL)ishidden
{
    UIImageView *tipV  = [[[[[[uvMainIcon subviews]objectAtIndex:uvMainIcon.subviews.count-1] subviews]objectAtIndex:index]subviews]objectAtIndex:2];
    UILabel *lb = [[tipV subviews]objectAtIndex:0];
    if (tips.length>2) {
        tipV.frame = [EpointExtendIconView getTipLongRect];
    }
    else
    {
        tipV.frame = [EpointExtendIconView getTipShort];
    }
    lb.frame = tipV.bounds;
    lb.text = tips;
    tipV.hidden = ishidden;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)refreshUIWithThreadGuid:(int)taskId andData:(NSObject *)obj
{
    if (taskId==LoadMainConfigTskId) {
        mainIconArray = (NSMutableArray*)obj;
        [self loadMainIconView];
    }
    else if (taskId==User_GetInfo_TaskId)
    {
        NSMutableArray *arr = (NSMutableArray*)obj;
        NSMutableArray *listData = [arr objectAtIndex:2];
        
        
        NSString *mailTips = [listData objectAtIndex:0];
        NSString *dbTips = [listData objectAtIndex:1];
        
        //更新邮件图标数量
        if (mailTips.intValue>0) {
            [self changeIconTips:1 tips:mailTips hidden:NO];
        }
        else
        {
            [self changeIconTips:1 tips:mailTips hidden:YES];
        }
        //更新待办图标数量
        
        if (dbTips.intValue>0) {
            [self changeIconTips:0 tips:dbTips hidden:NO];
        }
        else
        {
            [self changeIconTips:0 tips:mailTips hidden:YES];
        }
    }
    else if (taskId==1234)
    {
        [self hideMBPHUD];
    }
    else if (taskId==GenerationHeadImageTaskId)
    {
        [objMan manage:headImgView];
    }
}

-(void)viewDidAppear:(BOOL)animated
{
    if([[DBFrameService getConfigValue:@"mainChanged"] isEqualToString:@"1"]||
       [[DBFrameService getConfigValue:@"APPEXTENDCHANGED"]isEqualToString:@"1"])
    {
        [uvMainIcon removeFromSuperview];
        [self loadMainIconView];
        [DBFrameService setConfigValue:@"mainChanged" value:@"0"];
        
        [self loadExtendIconView];
        [DBFrameService setConfigValue:@"APPEXTENDCHANGED" value:@"0"];
    }
    
    [self startTask:@"User_GetInfo_Task" withParams:nil withTaskId:User_GetInfo_TaskId];
}

-(void)loadMainIconView
{
    int MainIconPanelNums = mainIconArray.count%4==0?mainIconArray.count/4:mainIconArray.count/4+1;
    CGFloat sceneBottomY = uvScene.frame.size.height+uvScene.frame.origin.y;
    [uvMainIcon removeFromSuperview];
    uvMainIcon = [self getIconView:mainIconArray rect:CGRectMake(0, sceneBottomY, AppWidth, 100*MainIconPanelNums)];
    [sv addSubview:uvMainIcon];
    [sv setContentSize:CGSizeMake(AppWidth, uvMainIcon.frame.origin.y+uvMainIcon.frame.size.height)];
    NSLog(@"svnum:%i",sv.subviews.count);
}

-(UIView *)getIconView:(NSMutableArray *)iArr rect:(CGRect)rect
{
    int MainIconPanelNums = iArr.count%4==0?MainIconPanelNums = iArr.count/4:iArr.count/4+1;
    
    UIView *MainIconView = [[UIView alloc]initWithFrame:rect];
    NSString* displayLine =  NSLocalizedString(@"DisplayGridLine", "");
    if ([displayLine isEqualToString:@"1"]) {
        for (int i=0; i<MainIconPanelNums; i++) {
            
            //加载边框
            UIView *uvPanel = [[UIView alloc]initWithFrame:CGRectMake(0, i*100, AppWidth, 100)];
            uvPanel.backgroundColor = [UIColor clearColor];
            
            UIImageView *ivLineTop = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, AppWidth, 1)];
            [ivLineTop setImage:[UIImage imageNamed:@"list_divider_line"]];
            [uvPanel addSubview:ivLineTop];
            
            UIImageView *ivLineBottom = [[UIImageView alloc]initWithFrame:CGRectMake(0, 99, AppWidth, 1)];
            [ivLineBottom setImage:[UIImage imageNamed:@"list_divider_line"]];
            [uvPanel addSubview:ivLineBottom];
            
            UIImageView *ivLine1 = [[UIImageView alloc]initWithFrame:CGRectMake(80, 0, 1, 100)];
            [ivLine1 setImage:[UIImage imageNamed:@"line_col"]];
            [uvPanel addSubview:ivLine1];
            
            UIImageView *ivLine2 = [[UIImageView alloc]initWithFrame:CGRectMake(160, 0, 1, 100)];
            [ivLine2 setImage:[UIImage imageNamed:@"line_col"]];
            [uvPanel addSubview:ivLine2];
            
            UIImageView *ivLine3 = [[UIImageView alloc]initWithFrame:CGRectMake(240, 0, 1, 100)];
            [ivLine3 setImage:[UIImage imageNamed:@"line_col"]];
            [uvPanel addSubview:ivLine3];
            
            if (i>0) {
                ivLineTop.hidden = YES;
            }
            [MainIconView addSubview:uvPanel];
        }

    }
    
    UIView *icoPanel = [[UIView alloc]initWithFrame:MainIconView.bounds];
    
    for (int i=0; i<iArr.count; i++) {
        
        EpointMainConfigModel *m = [iArr objectAtIndex:i];
        int icon_row = i/4;
        int icon_col = i%4;
        
        EpointExtendIconView *icon = [[EpointExtendIconView alloc]initWithFrame:CGRectMake(icon_col*80, 100*icon_row, 80,100) withHandler:^{
            if ([m.type isEqualToString:@"2"]) {
                NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
                [params setObject:m.dyUrl forKey:@"url"];
                [params setObject:m.modulename forKey:@"title"];
                EpointBrowerViewController *vc = [[EpointBrowerViewController alloc]init];
                vc.passParam = params;
                [self.navigationController pushViewController:vc animated:YES];
            }
            else if([m.type isEqualToString:@"1"])
            {
                
                NSData* aData = [m.paData dataUsingEncoding: NSUTF8StringEncoding];
                NSError *error;
                NSDictionary *json = [NSJSONSerialization JSONObjectWithData:aData options:kNilOptions error:&error];
                NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
                for (NSString *key in [json keyEnumerator]) {
                    [params setObject:[json objectForKey:key] forKey:key];
                }
                [params setObject:m.modulename forKey:@"title"];
                EpointPhoneViewController *c = [[NSClassFromString(m.launchclass) alloc]init];
                c.passParam = params;
                [self.navigationController pushViewController:c animated:YES];
            }
            else if ([m.type isEqualToString:@"3"])
            {
                if (![[UIApplication sharedApplication]canOpenURL:[NSURL URLWithString:m.launchclass]]) {
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:m.apkUrl]];
                }
                else
                {
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:m.launchclass]];
                }
            }
        }];
        icon.lbTitle.text = m.modulename;
        [icoPanel addSubview:icon];
        
        icon.ivIcon.url = [NSURL URLWithString:[EpointBizTools getUrl:[NSString stringWithFormat:@"mobileconfig/mainimg/%@",m.iconUrl]]];
//        [self setThemeColor:icon.ivIcon];
        [objMan manage:icon.ivIcon];
    }
    [MainIconView addSubview:icoPanel];
    return MainIconView;
}

-(void)loadExtendIconView
{
    NSArray *dataExtendArrQuery = [EpointExtendAppConfig findByCriteria:@""];
    NSMutableArray *dataExtendArr = [[NSMutableArray alloc]init];
    for (int i=0; i<dataExtendArrQuery.count; i++) {
        EpointExtendAppConfig *cg = [dataExtendArrQuery objectAtIndex:i];
        EpointMainConfigModel *em = [[EpointMainConfigModel alloc]init];
        em.moduleID = cg.moduleid;
        em.type = cg.type;
        em.isDefault = cg.isdefault;
        em.modulename = cg.modulename;
        em.position = cg.position;
        em.platform = cg.platform;
        em.dyUrl = cg.dyurl;
        em.paData = cg.padata;
        em.iconUrl = cg.iconurl;
        em.apkUrl = cg.apkurl;
        em.launchclass = cg.launchclass;
        em.packagename = cg.packagename;
        em.version = cg.version;
        em.tips = cg.tips;
        [dataExtendArr addObject:em];
    }
    
    if (dataExtendArr.count>0) {
        int uvExtentIconNums = dataExtendArr.count%4==0?dataExtendArr.count/4:dataExtendArr.count/4+1;
        CGFloat sceneBottomY = uvMainIcon.frame.size.height+uvMainIcon.frame.origin.y;
        [labExt removeFromSuperview];
        labExt = [[UILabel alloc]initWithFrame:CGRectMake(0, sceneBottomY, AppWidth, 40)];
        labExt.text = @"  扩展应用";
        labExt.backgroundColor = [UIColor clearColor];
        labExt.font = [UIFont systemFontOfSize:17];
        labExt.textColor = COLOR(128, 136, 149);
        labExt.shadowColor = [UIColor whiteColor];
        labExt.shadowOffset = CGSizeMake(0, 1);
        [sv addSubview:labExt];
        [uvExtendIcon removeFromSuperview];
        uvExtendIcon = [self getIconView:dataExtendArr rect:CGRectMake(0, labExt.frame.origin.y+labExt.frame.size.height, AppWidth, 100*uvExtentIconNums)];
        [sv addSubview:uvExtendIcon];
        [sv setContentSize:CGSizeMake(AppWidth, uvExtendIcon.frame.origin.y+uvExtendIcon.frame.size.height)];
    }
    else
    {
        [labExt removeFromSuperview];
        [uvExtendIcon removeFromSuperview];
        [sv setContentSize:CGSizeMake(AppWidth, uvMainIcon.frame.origin.y+uvMainIcon.frame.size.height)];
    }
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
